package com.region.spring.cloud.core;

import com.region.loadbalancer.listener.ConnectionListener;
import com.region.spring.boot.RegionAdapterProperties;
import com.region.spring.boot.RegionClientAutoConfiguration;
import com.region.spring.cloud.core.configure.SpringCloudCustomConfigurer;
import com.region.spring.cloud.core.listener.RegionCloudInstanceListener;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.util.Arrays;

/**
 * @author liujieyu
 * @date 2024/8/26 23:13
 * @description
 */
@Configuration
@ConditionalOnBean({DiscoveryClient.class})
@AutoConfigureBefore({RegionClientAutoConfiguration.class})
@EnableConfigurationProperties({RegionCloudAdapterProperties.class})
@Import({RegionCloudInstanceListener.class})
public class RegionCloudRegistrarAutoConfiguration {

    private final DiscoveryClient discoveryClient;

    private final RegionCloudAdapterProperties cloudProperties;

    private final RegionAdapterProperties adapterProperties;

    private final ConnectionListener[] connectionListeners;

    public RegionCloudRegistrarAutoConfiguration(DiscoveryClient discoveryClient,
                                                 RegionCloudAdapterProperties cloudProperties,
                                                 RegionAdapterProperties adapterProperties,
                                                 ObjectProvider<ConnectionListener[]> connectionListeners) {
        this.discoveryClient = discoveryClient;
        this.cloudProperties = cloudProperties;
        this.adapterProperties = adapterProperties;
        // Set automatically monitor
        this.adapterProperties.setAutoMonitor(false);
        this.connectionListeners = connectionListeners.getIfAvailable();
    }

    @Bean
    @ConditionalOnMissingBean
    public SpringCloudCustomConfigurer springCloudCustomConfigurer() {
        return new SpringCloudCustomConfigurer(this.discoveryClient, this.cloudProperties,
                this.connectionListeners != null ? Arrays.asList(this.connectionListeners) : null);
    }

}
